<template>
  <div id="roleDiv">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-select v-model="queryParams.grade" placeholder="请选择角色">
          <el-option label="超级管理员" value="1"></el-option>
          <el-option label="管理员" value="2"></el-option>
          <el-option label="普通用户" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入用户名/姓名"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
        >添加
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--            type="warning"-->
      <!--            plain-->
      <!--            icon="el-icon-download"-->
      <!--            size="mini"-->
      <!--            @click="handleExport"-->
      <!--            v-hasPermi="['system:role:export']"-->
      <!--        >导出</el-button>-->
      <!--      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange"
              style="margin-top: 10px">
      <el-table-column label="用户名" align="center" prop="username"/>
      <el-table-column label="真实姓名" align="center" prop="name"/>
      <el-table-column label="角色" align="center" prop="grade">
        <template slot-scope="scope">
          <p v-if="scope.row.grade==1">超级管理员</p>
          <p v-else-if="scope.row.grade==2">管理员</p>
          <p v-else-if="scope.row.grade==3">普通用户</p>
          <p v-else>未知</p>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status == 0 ? "启用" : "禁用" }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="300"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdateStatus(scope.row)"
          >修改状态
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改角色管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"/>
          <span><font size="2px" color="#696969">限4-16个字母和数字，必须以字母开头，不区分大小写</font></span>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"/>
        </el-form-item>
        <el-form-item label="角色" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择">
            <el-option key="1" label="超级管理员" value="1"></el-option>
            <el-option key="2" label="管理员" value="2"></el-option>
            <el-option key="3" label="普通用户" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0" value="0">启用</el-radio>
            <el-radio label="1" value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addUser, updateUser, getUser, deleteUser, updateStatus} from "@/api/user/login"
import {MessageBox} from "element-ui";

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色管理表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        number: null,
        isDel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "真实姓名不能为空", trigger: "blur"},
        ],
        username: [
          {required: true, message: "用户名不能为空", trigger: "blur"},
          {
            validator: this.nameRule, // 使用自定义验证函数
            trigger: 'blur'
          }
        ],
        password: [
          {required: true, message: "密码不能为空", trigger: "blur"},
          {
            validator: this.passwordRule, // 使用自定义验证函数
            trigger: 'blur'
          }
        ],
        grade: [
          {required: true, message: "必须选择角色", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询账号管理列表 */
    getList() {
      this.loading = true;
      getUser(this.queryParams).then(response => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = row;
      this.form.grade=String(row.grade);
      this.form.status=String(row.status);
      this.open = true;
      this.title = "修改角色";
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form)
      // this.$refs["form"].validate(valid => {
      //   if (valid) {
          const action = this.form.id != null ? updateUser : addUser; // 选择函数
          const successMessage = this.form.id != null ? "修改成功" : "新增成功"; // 成功提示
          const errorMessage = this.form.id != null ? "修改失败" : "新增失败"; // 失败提示

          action(this.form).then(response => {
            if (response.code == 200) {
              this.$message.success(successMessage);
              this.open = false;
              this.getList();
            } else {
              this.$message.error(errorMessage);
            }
          }).catch(error => { // 添加错误处理
            console.error(error);
            this.$message.error("操作失败，请稍后重试");
          });
        // }
      // });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      MessageBox.confirm(
          '确定要删除该项吗？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        deleteUser(ids).then(response => {
          if (response.code == 200) {
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败")
          }
        });
        this.getList();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /** 修改状态 */
    handleUpdateStatus(val) {
      MessageBox.confirm(
          '确定要禁用/启用该项吗？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        updateStatus(val).then(response => {
          if (response.code == 200) {
            this.$message.success("修改成功")
            this.getList();
          } else {
            this.$message.error("修改失败")
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        });
      });
    },
    nameRule(rule, value, callback) {
      const regex = /^[a-zA-Z][a-zA-Z0-9]{3,15}$/;
      if (!regex.test(value)) {
        callback(new Error('不符合规则'));
      } else {
        callback()
      }
    },
    passwordRule(rule, value, callback) {
      const regex = /^\d+$/;
      if (regex.test(value)) {
        return true; // 密码有效
      } else {
        return callback(new Error('密码由纯数字组成')); // 密码无效
      }
    }
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('system/role/export', {
    //     ...this.queryParams
    //   }, `role_${new Date().getTime()}.xlsx`)
    // }
  }
};
</script>

<style>
#roleDiv {
  padding: 5px;
}
</style>
